<template>
  <el-menu
    :default-active="activeMenu"
    :router="true"
    :unique-opened="uniqueOpened"
    :mode="mode"
    :collapse="collapse"
    @select="handleSelect"
  >
    <menu-item
      v-for="route in menuRoutes"
      :key="route.path"
      :item="route"
      :base-path="route.path"
    />
  </el-menu>
</template>

<script setup>
import { computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import MenuItem from "./MenuItem.vue";

const props = defineProps({
  mode: {
    type: String,
    default: "vertical",
  },
  collapse: {
    type: Boolean,
    default: false,
  },
  uniqueOpened: {
    type: Boolean,
    default: false,
  },
});

const route = useRoute();
const router = useRouter();

// 获取过滤后的菜单路由
const menuRoutes = computed(() => {
  return filterRoutes(router.options.routes);
});

// 当前激活的菜单
const activeMenu = computed(() => {
  const { meta, path } = route;
  return meta?.activeMenu || path;
});

// 过滤需要隐藏的路由
const filterRoutes = (routes) => {
  return routes.filter((route) => {
    // 隐藏没有meta的路由或明确设置hide的路由
    if (!route.meta || route.meta.hide) {
      return false;
    }

    // 如果有子路由，递归过滤
    if (route.children && route.children.length > 0) {
      route.children = filterRoutes(route.children);
      // 如果过滤后子路由为空，且没有设置alwaysShow，则隐藏该路由
      if (route.children.length === 0 && !route.meta.alwaysShow) {
        return false;
      }
    }

    return true;
  });
};

const handleSelect = (key) => {
  console.log("菜单选中:", key);
};
</script>
